<template>
  <view>
    <view class="goods-list">
      <view v-for="(item, i) in goodsList" :key="i" @click="gotoGoodsDetail(item)">
        <!-- 为 my-goods 组件动态绑定 goods 属性的值 -->
        <my-goods :goods="item"></my-goods>
        <!-- 使用封装好的组件，传入goods即可 -->
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        queryObj: {
          // 查询关键词
          query: '',
          // 商品分类id
          cid: '',

          // 页码值
          pagenum: 1,
          // 每页显示多少条数据
          pagesize: 10
        },
        goodsList: [], // 商品列表
        total: 0, // 商品数据总量
        flag: false, // 设置请求节流阀
      };
    },

    methods: {
      async getGoodsList() {
        this.flag = true;
        // 发起请求
        const {
          data: res
        } = await uni.$http.get('/api/public/v1/goods/search', this.queryObj)
        this.flag = false;
        if (res.meta.status !== 200) return uni.$showMsg()
        // 为数据赋值
        this.goodsList = [...this.goodsList, ...res.message.goods];
        this.total = res.message.total;
      },
      gotoGoodsDetail(item){
        uni.navigateTo({
          url: "/subpkg/goods_detail/goods_detail?goods_id=" + item.goods_id
        })
      }
    },
    onLoad(options) {
      // 保存页面传递来的参数
      this.queryObj.query = options.query || ''
      this.queryObj.cid = options.cid || ''
      this.getGoodsList();
    },
    // 监听上拉触底
    onReachBottom() {
      // 判断数据是否请求完毕
      if (this.queryObj.pagenum * this.queryObj.pagesize >= this.total) return uni.$showMsg("我可是有底线的~");
      if (this.flag) return; // 节流
      this.queryObj.pagenum += 1;
      this.getGoodsList();
    },
    // 监听下拉刷新
    onPullDownRefresh() {
      // 重置关键数据
      this.queryObj.pagenum = 1;
      this.total = 0;
      this.flag = false;
      this.goodsList = [];

      // 重新发送请求
      this.getGoodsList();
      uni.stopPullDownRefresh();
    }
  }
</script>

<style lang="scss">
</style>
